import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

//创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:5198/',
    timeout: 5000,
});

//请求拦截器
service.interceptors.request.use(config => {
    //携带token
    let token = window.localStorage.getItem('token');
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token;
    };
    return config;
}, err => {
    return Promise.reject(err);
});

//响应拦截器
service.interceptors.response.use(response => {
    if (response.status === 200 || response.status === 201) {
        return response;
    } else {
        ElMessage({
            message: '请求错误',
            type: 'error',
            plain: true,
        });
    }
}, err => {
    if (err.code == 'ERR_NETWORK') {
        ElMessage({
            message: '网络错误',
            type: 'error',
            plain: true,
        });
    } else if (err.status === 400) {
        ElMessage({
            message: err.response.data,
            type: 'error',
            plain: true,
        });
    }
    else if (err.status === 401) {
        if (route == undefined) {
            ElMessage({
                message: '用户名或密码错误',
                type: 'warning',
                plain: true,
            });
        } else {
            router.push('/Login');
        }
    } else if (err.status === 403) {
        ElMessage({
            message: '未授权',
            type: 'warning',
            plain: true,
        });
    } else if (err.status === 404) {
        ElMessage({
            message: err.response.data,
            type: 'warning',
            plain: true,
        });
        // router.push('/404')
    } else if (err.status === 405) {
        ElMessage({
            message: '不支持的请求方法',
            type: 'warning',
            plain: true,
        });
    } else if (err.status === 409) {
        ElMessage({
            message: '请求数据已存在',
            type: 'warning',
            plain: true,
        });
    } else if (err.status === 500) {
        ElMessage({
            message: err.response.data,
            type: 'error',
            plain: true,
        });
    }
    return err.response;
});

//导出
export default service;